using System;
using System.Collections.Generic;
using UnityEditor;

namespace Yoozoo.Editor.Utils
{
    public class DefineSymbolSetup : IDisposable
    {
        private readonly List<string> defineSymbols = new List<string>();
        private readonly BuildTargetGroup targetGroup;

        public DefineSymbolSetup()
        {
#if UNITY_IOS
            targetGroup = BuildTargetGroup.iOS;
#elif UNITY_ANDROID
            targetGroup = BuildTargetGroup.Android;
#elif UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
            targetGroup = BuildTargetGroup.Standalone;
#endif
            string defineSymbolString = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
            defineSymbols.AddRange(defineSymbolString.Split(';'));
        }

        /// <summary>
        /// 更新默认宏定义
        /// </summary>
        /// <param name="symbolsName">需要修改的宏名称</param>
        /// <param name="state">true：增加，false:移除</param>
        public void UpdateDefineSymbol(string symbolsName, bool state)
        {
            if (string.IsNullOrEmpty(symbolsName))
            {
                return;
            }

            bool isContains = defineSymbols.Contains(symbolsName);

            Debug.Log($"UpdateDefineSymbol:{symbolsName,100} state:{state,5} isContains:{isContains, 5}");
            if (isContains && !state)
            {
                defineSymbols.Remove(symbolsName); //移除
                Debug.Log("UpdateDefineSymbol: Remove " + symbolsName);
            }
            else if (!isContains && state)
            {
                defineSymbols.Add(symbolsName); //增加移除
                Debug.Log("UpdateDefineSymbol:   Add " + symbolsName);
            }
        }

        public void Dispose()
        {
            var defines = string.Join(";", defineSymbols.ToArray());
            Debug.LogFormat("UpdateDefineSymbol: PlayerSettings.SetScriptingDefineSymbolsForGroup {0} {1}", targetGroup, defines);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines);
        }
    }
}
